from datetime import datetime, timedelta

from flask import Blueprint, render_template, jsonify, request, make_response

from app.models.metadata import Subject
from app.utils import generate_user_id

bp = Blueprint('main', __name__)


def get_user_id():
    """获取或创建用户ID"""
    user_id = request.cookies.get('user_id')
    if not user_id:
        user_id = generate_user_id()
    return user_id


@bp.route('/')
@bp.route('/index')
def index():
    # 创建响应对象
    response = make_response(render_template('index.html'))

    # 如果用户没有ID，设置一个新的ID
    if not request.cookies.get('user_id'):
        user_id = generate_user_id()
        # 设置cookie，过期时间为30天
        expires = datetime.now() + timedelta(days=30)
        response.set_cookie('user_id', user_id, expires=expires, httponly=True)

    return response


@bp.route('/api/subjects', methods=['GET'])
def get_subjects():
    """获取所有科目"""
    return jsonify([{"value": subject.value, "name": subject.value} for subject in Subject])
